package com.cloudfun.campusshare.device.protocol.consumer;

import com.cloudfun.campusshare.common.constant.Code;
import com.cloudfun.campusshare.common.exception.BusinessException;
import com.cloudfun.campusshare.device.protocol.response.Alarm;
import com.cloudfun.campusshare.device.protocol.response.BaseMessage;
import com.cloudfun.campusshare.service.DeviceAlarmService;
import com.cloudfun.msgsubscribe.DeviceInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by Huqin on 2020/2/5
 */
@Slf4j
@Service
public class DeviceAlarmConsumer implements DeviceMessageConsumer {

    @Autowired
    private DeviceAlarmService deviceAlarmService;

    @Override
    public boolean support(Class<?> clazz) {
        return Alarm.class.isAssignableFrom(clazz);
    }

    @Override
    public void doConsumer(BaseMessage message, String deviceName) {
        Alarm alarm = (Alarm) message;
        DeviceInfo alarmInfo = new DeviceInfo();
        alarmInfo.setImei(deviceName);
        alarmInfo.setTimestamp(message.getTimestamp());
        // 故障解除
        if (alarm.isAlarmCancel()) {
            // 内部消费
            deviceAlarmService.onAlarmCancel(deviceName);
            alarmInfo.addAlarm("alarmCancel");
        } else {
            try {
                Map<?, ?> returnMap = BeanUtils.describe(alarm);
                returnMap.remove("class");
                returnMap.remove("valid");
                returnMap.remove("ack");
                returnMap.remove("timestamp");
                for (Map.Entry<?, ?> entry : returnMap.entrySet()) {
                    String fieldName = (String) entry.getKey();
                    String fieldValue = (String) entry.getValue();
                    if (StringUtils.isBlank(fieldValue)) {
                        continue;
                    }
                    if (Boolean.parseBoolean(fieldValue)) {
                        alarmInfo.addAlarm(fieldName);
                    }
                }
                // 内部消费
                deviceAlarmService.onAlarm(alarmInfo);
            } catch (Exception e) {
                log.error("设备告警处理异常：", e);
                throw new BusinessException(Code.SYSTEM_ERROR);
            }
        }
    }
}
